// 接收消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { 
  if(message.type === "download") { 
    chrome.downloads.download(
      {
        url: message.data,
        filename: "downloaded_image.jpg",
        saveAs: true
      },
      function (downloadId) { 
        console.log(downloadId)
      }
    )
      
  }
});

chrome.runtime.onInstalled.addListener(() => { 
  // 创建右键菜单
  chrome.contextMenus.create({
    id: "menu-1",
    type:"normal",
    title: "批量下载图片",
    contexts: ["all"],
  })

  // // 创建子菜单
  // chrome.contextMenus.create({
  //   id: "menu-2",
  //   type:"normal",
  //   title: "右键菜单-1",
  //   contexts: ["all"],
  //   parentId: "menu-1"
  // })

  // // 创建子菜单
  // chrome.contextMenus.create({
  //   id: "menu-3",
  //   type:"normal",
  //   title: "右键菜单-2",
  //   contexts: ["all"],
  //   parentId: "menu-1"
  // })
})


chrome.contextMenus.onClicked.addListener((data) => { 
  if(data.menuItemId === "menu-1") { 
    // todos
    onMenuClick()
  }
})

async function onMenuClick() { 
  const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });

  // 由于现在在background.js中，我们需要发送消息告诉页面，需要获取图片元素
  // 页面获取消息，然后反馈图片信息给background.js
  const response = await chrome.tabs.sendMessage(tab.id, { type: "images" })
  
  var data = response || [];

  chrome.storage.local.get(["filterURL"]).then((result) => { 
    var value = result["filterURL"];
    if (value) { 
      data = data.filter((src)=>src.indexOf(value) !== -1).map(download)
    }
  })

  // data.map(download)
}


function download(url) { 
  const filename = url.split("/").pop();

  chrome.downloads.download({
    url,
    filename: "./all_images/" + filename
  })
}